# Maintainer: Gustavo Alvarez <sl1pkn07@gmail.com>
# Contributor: Mikhail Vorozhtsov <mikhail.vorozhtsov@gmail.com>
# Contributor: Nagisa <simonas@kazlauskas.me>
# Contributor: Misc <andreas.reis@gmail.com>
# Contributor: Jeagoss <jgoliver@jeago.com>
# Contributor: Saikrishna Arcot <saiarcot895@gmail.com> (Author of https://github.com/saiarcot895/chromium-ubuntu-build/blob/master/debian/patches/enable_vaapi_on_linux.diff)

#########################
## -- Build options -- ##
#########################

#XXX: will always use system clang!(not bundled, and not gcc!)
#_use_clang=1           # Use clang compiler (system). Results in faster build and smaller chromium.
#_use_bundled_clang=0   # Use bundled clang compiler (needs build). NOTE: if use this option , '_use_clang' need set to 1
_use_ccache=1          # Use ccache when build
_use_gtk3=1            # If set 1, then build with GTK3 support, if set 0, then build with GTK2
inTMPFS=1 # 1 means compile in /tmp (assumed u have enough ram and it's tmpfs)
#^ this currently takes 1.3G when done
system_ffmpeg=1 # if 1 then make chromium use system's ffmpeg instead of its own! #set to 1 to work around this bug: https://bugs.chromium.org/p/chromium/issues/detail?id=629695
#XXX also comment out(when=0) this patch below chromium-system-ffmpeg-r3.patch

##############################################
## -- Package and components information -- ##
##############################################
pkgname=chromium-dev
pkgver=55.0.2878.0_r16359.6e15573
_launcher_ver=5
pkgrel=1
pkgdesc="The open-source project behind Google Chrome Dev Channel"
arch=('i686' 'x86_64')
url='http://www.chromium.org'
license=('BSD')
depends=('desktop-file-utils'
         #'icu'
         'jsoncpp'
         #'libsrtp'
         'libwebp'
         'libxslt'
         'libxss'
         'minizip'
         'perl-file-basedir'
         'nss'
         'pciutils'
         #'re2'
         'snappy'
         'speech-dispatcher'
         'speex'
         'xdg-utils'
         #'opus'
         #'protobuf'
         #'libevent'
         'libvpx'
         'ffmpeg'
         )
makedepends=('libexif'
             'elfutils'
             'gperf'
             'ninja'
             'perl-json'
             'python2-beautifulsoup4'
             'python2-html5lib'
             'python2-simplejson'
             'python2-jinja'
             'python2-ply'
             'subversion'
             'yasm'
             'git'
             'imagemagick'

#me
'depot-tools-git'
'libtinfo' #when GN build! it's on aur/libtinfo and in my packages!

             #src: https://chromium.googlesource.com/chromium/src/+/master/docs/linux_build_instructions.md#Arch-Linux
             'python'
             'perl'
             'gcc'
             'gcc-libs'
             'bison'
             'flex'
             'gperf'
             'pkgconfig'
             'nss'
             'alsa-lib'
             'gconf'
             'glib2'
             'gtk2'
             'nspr'
#             'ttf-ms-fonts' #it's there on AUR only!
             'freetype2'
             'cairo'
             'dbus'
             'libgnome-keyring'


             )
optdepends=(
####'chromium-pepper-flash-dev: PPAPI Flash Player Dev Channel 64bits only'
            'chromium-widevine-dev: Widevine plugin eg: Netflix Dev Channel 64bits only'
            #
            'kdebase-kdialog: Needed for file dialogs in KDE4/KF5'
            'kdialog-frameworks-git: Needed for file dialogs in KF5'
            #
            'kwalletmanager: Needed for storing passwords in KWallet in KF5'
            #
            'libexif: Need for read EXIF metadata'
            'ttf-font: For some typography'
            )
conflicts=('chromedriver' 'chromium')

allpatches=(
#0200_no_warnings_as_errors.patch
#0300_use_system_clang.patch
#0500_message_center_disabled.patch
#0600_fix_AutofillDialogController.patch
##0800_small_fixes.patch
#0900_autofill_disabled.patch
#1000_pepper_compile_error.patch
#1100_plugins_disabled.patch
#1200_signin_fix.patch
#1300_background_fix.patch
##1400_hotword_disabled.patch
#1400_make_linking_work.patch
no_sysroot.patch
#desktop_capture_controller_fail.patch
#gcd_mdns_fix.patch
#no_ppapi.patch
#more_pepper.patch
#pdf_fix.patch
#foo_widevine.patch
media_build.patch
#OnReadFrameDone.patch
#FPE_INTDIV.patch#don't set this so we can test that the kernel one works when no665wo is set in /proc/cmdline
handlebit_size0.patch
chromium-system-ffmpeg-r3.patch
#clipboard_nospam.patch  #got removed by commit c46a48577b1b750f2561d7f3aeb45e354b45d3c4

modified_chromium-hotwording-2403.patch

chromium-52.0.2743.116-unset-madv_free.patch

all.patch

invalid_chan_msg.patch
google_search_engine_url.patch
#nostackprotection.patch
#crazycflagstest.patch
crazycflagstest_Ofast.patch
#crazycflagstest_O2.patch
chromium-system-jinja-r11.patch
distiller_nospam.patch
DesktopCaptureDevice.patch
noscreencapture.patch
)

installfil=chromium-dev.install
source=(
#####"https://commondatastorage.googleapis.com/chromium-browser-official/chromium-${pkgver}.tar.xz"
        "$installfil"
        "chromium-launcher-${_launcher_ver}.tar.gz::https://github.com/icanrealizeum/chromium-launcher/archive/v${_launcher_ver}.tar.gz"
        'chromium-dev.svg'
        # Patch form Gentoo
        #'https://raw.githubusercontent.com/gentoo/gentoo/master/www-client/chromium/files/chromium-system-ffmpeg-r2.patch'
#        'https://raw.githubusercontent.com/gentoo/gentoo/master/www-client/chromium/files/chromium-system-jinja-r11.patch'
        'https://raw.githubusercontent.com/gentoo/gentoo/master/www-client/chromium/files/chromium-system-zlib-r0.patch'
##it is changed        'https://raw.githubusercontent.com/gentoo/gentoo/master/www-client/chromium/files/chromium-linker-warnings-r0.patch'
        # Misc Patches
        #'enable_vaapi_on_linux.diff' ###'https://raw.githubusercontent.com/saiarcot895/chromium-ubuntu-build/master/debian/patches/enable_vaapi_on_linux.diff'
        'minizip.patch::http://pastebin.com/raw/QCqSDam5'
#        # Patch from crbug (chromium bugtracker)
#        'chromium-widevine-r1.patch' # https://crbug.com/473866

        #own patches
        "${allpatches[@]}"
        )

##"$(curl -sL https://gsdview.appspot.com/chromium-browser-official/?marker=chromium-${pkgver}.tar.xz.hashes | awk -v FS='<td>"' -v RS='"</td>' '$0=$2' | head -n1)"
#          "$(curl -sL https://commondatastorage.googleapis.com/chromium-browser-official/chromium-${pkgver}.tar.xz.hashes | grep sha1 | cut -d " " -f3)"
sha512sums=('c675a4bfc2b1588fc876172cea003e42e812da797eeaf45b332f3554f22020d66cf445762500d345725c47c23f8b63ed30fc02135db5edd72033f13da51292a3'
            'f3480752413ac722d4b70f8ae637303b3b958e27677c482dc75be8a52285c1aa4db1ce670faefd460308548f2d861a935c12c8de24284edad58902cc89aac4a5'
            'e13f13871cbbaf76dfdbd3c89619116d1264805562bffcef46380d59bd54483267a4c917bb4b8423cedd0e0ce96f15d5b3768eb533d8ec12fb825eda192c4042'
            'ea7b9da8bf504583e0753ed2d69e95e6d2579bb9640b52b9d575966f495bd4dc15ec94fb35ad9877a736dceed946a38dccac028a4130326fda3f7ad7dfb3b07c'
            '2108a3d40cef30de917af30945783da3b095cefac18ce7a37e9c6d184ede152dbc1671fa9fc89a1f183ab8b4b13f3237ec7834837a9c63a39ff31b26215f2320'
            '49534af6e37343732be13d6b704b81f77cdf6cba631b75514cacca795d244c4fbf960ddd634cbcb72f5f6c05af978d3515e2865d4eaf04a990bb6dfe098f550c'
            '305c09ca37cfeb290f7249c3d69679555fa74fb2a030a3ea8734b9ab2a045af17890813cfecb4add20b1e54e0476049a815fb29a3cdb5a30bd07c4281750f020'
            '2314a9ce1cc4327ff03d574ffb0bcc2f2d642ce68fc558c1c772e61922e078e02f43684088452f9513382ddde5ec344554e1cfa85d195033b49261466c779d08'
            '72c9fe7b966555c695c0cb54fa3fd708d12fb3192671eaec670108bc5e4616510434bbd9cfd49d09deb83e5b980e64336bf940be2d97b869ca763a3527a7bfeb'
            '3b1d95b126bec820bd0d92e5050742196ebd1c1657bf8e33854633fb0c4be2f33f777312d53eb048043d7f91c3491bc957b2e98723b2d7de58fa114255e40d7c'
            '32b2240509cbe7d6e3e9f38003d7f6ff94f8bd03942661a10946bb14f74e3ace100f61beb88215b3b95aa3236001cc81dbfa2c0469f5ade83e22ee2691b79627'
            'fa49ffd7ededb09ae85ca74abeeb61ff63610b9423cbdbbb3fc2c43c9fa48e0e15386b7daf126e7b51214fb565f37d3dded0ee39fefbe3fbb66694095420b3f0'
            '5e4178efd5f575d66f11940859375b5260a7fa384c90f30766988c89813055b9ae3b9c4fa9eaad4ac4dfce3faa6c82bb0381a13e5b3e0dfbdadc73d5456add89'
            'b4d3581f688efa18d94fd617a4364f36c471b746b6e899cfe0a7f7dd575dae59010d42bb68e6565b98a53e37a81dddfa913cde9c7cdf19716861ee9bb6d61f95'
            '6d5992d77c3ab0b34b376d81852911521dce4caba5bbadce7e894b31b7046362e60896e70d91ae7cb91dd05cb7c868475fce68d260b21f0ba3c0c97f42dbce03'
            '0c0a5a3ac24191417504ce92306e459ffc84c4cf39123d91992fcfb54df2c69cb373c48454343d3fb66a4f352d1c8bbefb15341b34e44a6798b47951f4c113ee'
            'b61202488cd364990a431b5be994680f1141c34784dabbf3f6049b70618af3c2a78c603e6e9d6be7f570d660e9e937f509fe49a7a15efd590fde0b38a9c616eb'
            'acc34998b53c2b17e74afedd56d8aee6e49d18f4761fd10eb156f5e5dd41460344494d65152a0fbd2cf234cdb7d01fe8533afc48b015c95a9666c246e566f0a7'
            '6a277d07d2e83819aa3c141a663c5e67e8eef4a2da1ca2817b457aa3accc501bd03900168e63bfb0095123d11046687925a5f49ec4979bb53700ab7069e9e4c9')
options=('!strip' 'ccache' '!distcc')
#XXX: not distcc beccause: distccd[16604] (dcc_execvp) ERROR: failed to exec ../../../home/z/build/1packages/chromium-dev-git/fetch_gclient_base/checkout_root/src/third_party/llvm-build/Release+Asserts/bin/clang++: No such file or directory

install="$installfil"
_folder="${startdir}/fetch_gclient_base/checkout_root"
_srcfolder="${_folder}/src"

_reldir="out/Default"
if test "$inTMPFS" = "1"; then
  _reldir="/tmp/${_reldir}"
fi

################################################
## -- Don't touch anything below this line -- ##
################################################

# Google API keys (see http://www.chromium.org/developers/how-tos/api-keys)
# NOTE: These are for Arch Linux use ONLY. For your own distribution, please
# get your own set of keys. Feel free to contact foutrelis@archlinux.org for
# more information.
#_google_api_key="AIzaSyDwr302FpOSkGRpLlUpPThNTDPbXcIn_FM"
#_google_default_client_id="413772536636.apps.googleusercontent.com"
#_google_default_client_secret="0ZChLK6AxeA3Isu96MkwqDR4"



# Need you use clang?
#if [ "${_use_clang}" = "1" ]; then
  makedepends+=('clang')
#fi
if [ "${_use_bundled_clang}" = "1" ]; then
  makedepends+=('cmake'
                'ocaml'
                'libffi'
                'chrpath'
                )
fi

# Build with GTK3?
if [ "${_use_gtk3}" = "1" ]; then
  depends+=('gtk3')
   makedepends+=('gtk2')
  _launcher_gtk='GTK=3'
  optdepends+=('libappindicator-gtk3: Needed for show systray icon in the panel in plasma-next (KF5)')
elif [ "${_use_gtk3}" = "0" ]; then
  depends+=('gtk2')
  optdepends+=('libappindicator-gtk2: Needed for show systray icon in the panel in plasma-next (KF5)')
fi

# Need you use ccache?
if [ "${_use_ccache}" = "1" ]; then
  makedepends+=('ccache')
fi


################################################
getchromiumver() {
    pushd -- "${_srcfolder}" >/dev/null 2>&1
    export PATH="${srcdir}/python-path:$PATH"
    build/util/version.py -f chrome/VERSION -t "@MAJOR@.@MINOR@.@BUILD@.@PATCH@"
    #FIXME: allow tag --list first and if empty, do the version.py - if the latter fails pkgver won't be changed apparently; that's good because it will have to fail until version.py gets downloaded
    # tags dont exit with --nohistory: git tag --list --sort="-v:refname" | head -1
    popd -- >/dev/null 2>&1
}

pkgver() {
    cd "${_srcfolder}"
    printf "%s_r%s.%s" "$(getchromiumver)" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
    printf "%s_r%s.%s" "$(getchromiumver)" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)" >&2
}

removestuff() {
#use like this removestuff <<EOF
#file1
#folder2
#EOF
#XXX: looks like the above can't contain {} or *   well it can but it won't be expanded (globbing?)
  if test -z "$1"; then
    error "you didn't pass a folder name as parameter"
    exit 1
  fi

#  read -r -d '' -a templist <&0 || true  #prevent EOF returning exit code 1 and due to set -e fail PKGBUILD!

  msg2 "Removing stuff from folder '$1'"
  pushd "$1" >/dev/null
#  echo ${templist[@]}
#TODO: maybe foreach and make sure they do not contain a first slash! as they are meant to be relative to current folder
#  cat <<<"$templist" | 
  xargs --no-run-if-empty --verbose --exit rm -rf -- # <<< "${templist[@]}"  #XXX: stuff is already comming from stdin
  # ${templist[@]}
  popd >/dev/null
#  msg2 "done."
}

lepatch() {
#  echo $-
#  trap -p
  #since we're inside PKGBUILD we know `set -e` is on, so we don't save its state
  set +e
#  set +o pipefail #unaffected by the setting of this
  #now we need to save/restore the ERR trap or else it gets triggered regardless of the +e setting
  local restoretrap="`trap -p | grep -E "ERR$"`"
  #clear ERR trap so we don't fail when patch or grep fails
  trap -- "" ERR
#XXX: PKGBUILD has: set -e which is why the following fails when grep doesn't find strings even if you add ` ; true`:
  msg2 "patch $*" #XXX: $* because $@ adds \n after first param O_o so msg2 doesn't show the rest
  patch "$@" | grep -B10 -E "(FAILED --|ignored|The next patch|which does not)"
  local ps=("${PIPESTATUS[@]}") #gets reset after running any statement, so need to save it
  #local ps="${PIPESTATUS[@]}" #gets reset after running any statement, so need to save it
#  declare +g -a "ps"

  #restore
  set -e
  eval "$restoretrap" 
#  $restoretrap #yep, unquoted, but doesn't work:
  #/usr/bin/makepkg:274+ trap -- ''\''error_function' '$pkgfunc'\''' ERR
  #PKGBUILD: line 274: trap: $pkgfunc': invalid signal specification
  #actual reported line by trap -p is: trap -- 'error_function $pkgfunc' ERR

#  set -o pipefail
# dsaodhasiohdoa #should fail - ok that worked!
  patch_ec="${ps[0]}"
  grep_ec="${ps[1]}"
  if test "$grep_ec" -eq 0; then # -o "$patch_ec" -ne 0; then
    #grepping found strings - this is bad
    error "patching failed! reapply changes in .rej files above and remake the patch, update patch file and re-execute this. Everything else should be patched because we're using only one patch UNLESS it's the first jinja patch, see the cmd above; For 'Skipping patch.' you just need to ignore those and re-run ./makepatchu and put the updated patch in place"
    ret=126
  else
    if test "$patch_ec" -ne 0; then
      ret="$patch_ec"
      error "patch command failed! exit code: $ret"
    fi
  fi
  return $ret
}

prepare() {

  # Set Python2 path
  mkdir -p python-path
  ln -s /usr/bin/python2 "${srcdir}/python-path/python" || echo 'probably symlink already existed - ignoring'
  export PATH="${srcdir}/python-path:$PATH"

#set|grep -i error
#exit 1
  pwd
  mkdir -p "${_folder}"
  cd "${_folder}"

# fetch if first time, sync if any other time
  if test -d "${_srcfolder}" -a -f ".gclient"; then
#    if [ ! -f ".gclient" ]; then
#      error ".gclient must exist in `pwd` Something went too wrong! must run fetch instead"
#      exit 1
#    fi

#    pushd "${_srcfolder}"
#    #overwrite all changes, usually made by us in this prepare() function
#    #let's hope user hasn't made any, they will be lost only when using checkout below (commented out now)
#    #changes will be stashed
#    #this is needed for gclient sync to work below
#
##fails
##    "${srcdir}/pythonic" build/linux/unbundle/replace_gyp_files.py "${_use_system[@]}" --undo
#
#    for each in ${_use_system[@]}; do
#      each2="$(echo -n "$each" | sed -e "s|.*_\(.*\)=[0-9]|\1|")"
#      msg2 "cleaning $each2"
#      _fold="third_party/${each2}"
#      if [ -d "$_fold" ]; then
#        _cleanfolder "${_fold}"
#      else
#        warning "ignoring inexistent folder $_fold"
#      fi
#    done

#    _cleanfolder "third_party/WebKit" #because of the jinja-r7.patch
#    _cleanfolder "third_party/webrtc"

#    popd

    msg2 "discarding changes..."
    gclient recurse --no-progress -- git checkout -- . >/dev/null || echo "ignoring failure" # >/dev/null
#    gclient recurse --no-progress -- git stash >/dev/null || echo "ignoring failure" # >/dev/null
#    gclient recurse --no-progress -- git stash clear >/dev/null || echo "ignored fails - because it's probably first run with empty src folder"
    rm -v -- "${_srcfolder}/content/common/va_wayland.sigs" ||true #created by the patch: enable_vaapi_on_linux.diff
    msg2 "sync-ing from the internet"
    pushd "${_srcfolder}"
    find . -type f -name '*.sedified' -or -type f -name '*.rej' -or -type f -name '*.cedified' | xargs rm -f -- 
#TEMP:    find . -type f -name '*_browsertest.*' | xargs rm -f --
#    TODO: is this really needed?: guess so, but should check updating instructions again sometime
    if test -d '.git'; then
      msg2 "git rebase-update aka git pull, sort of"
#      git pull --verbose --tags --depth=1  || ( git checkout master && git pull --tags --depth=1 --verbose )
#      git pull --progress --verbose || ( git checkout master && git pull --verbose --progress )
#good last:      git pull --verbose || ( git checkout master && git pull --verbose ) || echo "ignoring - because it's probably first run with empty src folder"


       git prune
       rm -- .git/gc.log || true
       git rebase-update
       #src: https://dev.chromium.org/developers/how-tos/get-the-code
       #//fixed: Cannot rebase-update with detached head + uncommitted changes.
       #//only the .keep filename is present/untracked! ok we remove it and keep .gitattributes

       #See "git help gc" for manual housekeeping.
       #error: The last gc run reported the following. Please correct the root cause
       #and remove .git/gc.log.
       #Automatic cleanup will not be performed until the file is removed.
       #warning: There are too many unreachable loose objects; run 'git prune' to remove them.

    fi
    popd
    #-vvv
    
    #"${srcdir}/pythonic"
#    gclient update --nohooks -v --no-history --jobs 8
#ok: need to modify .gclient_entries before syncing from internet! but it's part of gclient.py
#    updgclient_entries
    #gclient sync -vvv --nohooks --no-history --jobs 1
    msg2 "gclient sync (takes 33min on first time, on 13Mbps download, .git dir will be 776MiB and the whole src dir over 7GiB)"
    #--with_tags  #doesn't fetch tags if repo is already fetched
    gclient sync --nohooks --no-history --jobs 8  #not using -v , in order to be quiet; ok --shallow is bad, apparently!
#first time:
#real 33m31.809s
#user  11m25.590s
#sys 12m0.301s

    pwd
    gnexe="${_srcfolder}/buildtools/linux64/gn"
    if ! test -f "$gnexe"; then
      msg2 "gn executable isn't there, so this is probably the first run"
      msg2 "downloading it now..."
      download_from_google_storage -v --no_auth --no_resume --platform='linux*' --bucket chromium-gn -s src/buildtools/linux64/gn.sha1 || true
      #| grep -v -- 'CommandException: Invalid command "stat".'
      #^ this will fail with: "CommandException: Invalid command "stat"."
      # //yeah this didn't seem to work anyway: so using that grep which only returns 1 if that pattern isn't found should work around this and still fail if something else happened - but we can't see it :) unless using that -v to show anything other than that pattern
      #new error: Failed to fetch file gs://chromium-gn/feb65590433fab827a05b0b5fd6d8298aa572a25 for src/buildtools/linux64/gn. [Err: CommandException: option -o not recognized]
    fi
    if ! test -x "$gnexe"; then
      chmod a+x "$gnexe"
    fi
  else
    error "unsupported! the src folder '${_srcfolder}' must exist and .gclient file as a sibling too!"
    exit 22
#    msg2 "no src folder '${_srcfolder}' fetching..."
#    msg2 "Note: incomplete fetches should be restarted after you remove the src folder! (or so fetch says: that it doesn't support incomplete fetches)"
#    fetch --nohooks --no-history chromium

    #XXX: this patch is kinda useless to do after the fetch, because it already fetched everything that the patch is trying to exclude
#    patch -p1 -i "${srcdir}/$patchavoidfetch"
#    updgclient_entries
    # ^ this runs: gclient sync --nohooks --no-history
    #TODO: now how can I put a  -v  in there?
    # [0:00:01] remote: Sending approximately 2.72 GiB ...        
    # with --no-history that is
  fi

  cd "${_srcfolder}"
  pwd

#XXX: remove ppapi stuff due to:
#In file included from ../../../home/z/build/1packages/chromium-dev-git/fetch_gclient_base/checkout_root/src/content/ppapi_plugin/ppapi_broker_main.cc:11:
#In file included from ../../../home/z/build/1packages/chromium-dev-git/fetch_gclient_base/checkout_root/src/content/ppapi_plugin/ppapi_thread.h:20:
#../../../home/z/build/1packages/chromium-dev-git/fetch_gclient_base/checkout_root/src/content/public/common/pepper_plugin_info.h:20:2: error: "Plugins should be enabled"
##error "Plugins should be enabled"
# ^
#1 error generated.

#more errors:
#../../../home/z/build/1packages/chromium-dev-git/fetch_gclient_base/checkout_root/src/chrome/browser/component_updater/widevine_cdm_component_installer.cc:38:10: fatal error: 'content/public/common/pepper_plugin_info.h' file not found
##include "content/public/common/pepper_plugin_info.h"
#         ^
#1 error generated.

#TODO add dir chrome/browser/plugins/

removestuff "." <<EOF
chrome/browser/extensions/api/gcd_private
browser/extensions/api/mdns
chrome/browser/extensions/api/mdns
content/ppapi_plugin
content/public/common/pepper_plugin_info.h
content/browser/renderer_host/pepper
chrome/common/widevine_cdm_constants.cc
chrome/common/widevine_cdm_constants.h
components/cdm/common/widevine_drm_delegate_android.cc
components/cdm/common/widevine_drm_delegate_android.h
components/cdm/renderer/widevine_key_system_properties.cc
components/cdm/renderer/widevine_key_system_properties.h
media/test/data/eme_player_js/widevine_player.js
third_party/widevine
device/serial
device/udev_linux
extensions/browser/api/serial
extensions/common/api/serial.idl
extensions/renderer/resources/serial_custom_bindings.js
EOF

removestuff "chrome/browser" <<EOF
pepper_broker_infobar_delegate.cc
pepper_broker_infobar_delegate.h
pepper_flash_settings_manager.cc
pepper_flash_settings_manager.h
renderer_host/pepper/device_id_fetcher.h
component_updater/pepper_flash_component_installer.h
component_updater/pepper_flash_component_installer.cc
component_updater/widevine_cdm_component_installer.h
component_updater/widevine_cdm_component_installer.cc
renderer_host/pepper
browsing_data/browsing_data_flash_lso_helper.h
EOF

removestuff "chrome/browser/extensions/api/image_writer_private" <<EOF
removable_storage_provider.cc
removable_storage_provider_chromeos.cc
removable_storage_provider_chromeos_unittest.cc
removable_storage_provider.h
removable_storage_provider_linux.cc
removable_storage_provider_mac.cc
removable_storage_provider_win.cc
EOF

#yes the dir doesn't even exist yet!
#grep -nF 'registry->RegisterFunction<Serial' /tmp/out/Default/gen/extensions/browser/api/generated_api_registration.cc
#and in dir: /home/z/build/1packages/chromium-dev-git/fetch_gclient_base/checkout_root/src/
# this doesn't return anything: grep -nirF SerialGetDevicesFunction
#XXX ok so it's getDevices function under interface Functions in namespace serial in file: extensions/common/api/serial.idl //XXX so how teh fuck does the first grep return results (esp. this SerialGetDevicesFunction) later on!?!!???

#  cd "chromium-${pkgver}"

  # Fix to save configuration in ~/.config/chromium
      #-e "s|'confdir': 'chromium'|'confdir': 'chromium'|" \
#  sed -e "s|'filename': 'chromium-browser'|'filename': 'chromium'|" \
#      -i chrome/chrome_exe.gypi
  #XXX chrome/chrome_exe.gypi got deleted due to obsoleted by BUILD.gn
  #the following is now in all.patch (caught)
#  sed -e 's|filename = "chromium-browser"|filename = "chromium"|' \
#      -i chrome/BUILD.gn

#  sed -e 's|config_dir.Append("chromium")|config_dir.Append("chromium-dev")|' \
#      -e 's|config_dir.Append("chrome-frame")|config_dir.Append("chrome-frame-dev")|' \
#      -i chrome/common/chrome_paths_linux.cc

  msg2 "Patching the sources"
  # Patch sources from Gentoo
#  lepatch -Np1 -i "${srcdir}/chromium-system-ffmpeg-r2.patch" #add/remove of this has no effect on this issue: https://bugs.chromium.org/p/chromium/issues/detail?id=422522#c354  FIXED by using system-ffmpeg and reported new here: https://bugs.chromium.org/p/chromium/issues/detail?id=629695
#  lepatch -Np0 -i "${srcdir}/chromium-system-jinja-r11.patch"
#  patch -p0 -i "${srcdir}/chromium-linker-warnings-r0.patch" #TODO: should set fatal_linker_warnings to false instead of applying this patch!

  # Misc Patches:
  #lepatch -Np1 -i "${srcdir}/enable_vaapi_on_linux.diff"
  lepatch -Np1 -i "${srcdir}/minizip.patch"

  # Patch from crbug (chromium bugtracker)
  # https://crbug.com/473866
#  lepatch -Np0 -i "${srcdir}/chromium-widevine-r1.patch"
#  sed 's|@WIDEVINE_VERSION@|The Cake Is a Lie|g' -i "third_party/widevine/cdm/stub/widevine_cdm_version.h"
#  pushd "${_srcfolder}"
#  mkdir -p -- third_party/widevine/cdm/stub
#  touch third_party/widevine/cdm/stub/widevine_cdm_version.h
#  popd
#XXX: ^ even if that existed, because it's not included in some main .gn(i) file, it won't be processed/seen!! so, I'll fix the 20 files which include that .h instead!

  for eachpatch in "${allpatches[@]}"; do
    lepatch -Np1 -i "${srcdir}/${eachpatch}"
  done

  ##
  msg2 "Fix libpng errors"
  pushd chrome/app/theme &> /dev/null
  export IFS=$'\n'
  for i in $(find . -name '*.png' -type f); do
    mogrify "${i}" &> /dev/null
  done
  export IFS=' '
  popd &> /dev/null

  # Make it possible to remove third_party/adobe
  #FIXME: is this really needed in GN? or only has effect with GYP? - no idea
#  echo > "${srcdir}/flapper_version.h"
  _flapfile="${srcdir}/flapper_version.h"
  [ -f "$_flapfile" ] || echo > "$_flapfile"

  _flags+=( -Dflapper_version_h_file="${_flapfile}" )

  # Remove most bundled libraries. Some are still needed.
#  msg2 "Removing unnecessary components to save space"
#  python2 build/linux/unbundle/remove_bundled_libraries.py ${_necesary[@]} --do-remove
#  rm -fr native_client/toolchain
#  rm -fr build/linux/debian*


#  msg2 "Make sure use Python2" don't need this due to PATH being set with a symlinked python to python2
#  find . -name '*.py' -exec sed -r 's|/usr/bin/python$|&2|g' -i {} +
#  find . -name '*.py' -exec sed -r 's|/usr/bin/env python$|&2|g' -i {} +

  touch chrome/test/data/webui/i18n_process_css_test.html

  msg2 "done sources"

  mkdir -p "${_reldir}"
##    gn --root=src gen /tmp/out/Default
    pwd #already in src

#    flac
#    harfbuzz-ng
#    libevent
#    libxml
#    libxslt
#    snappy
#    yasm
local gn_system_libraries=(
    libvpx
    ffmpeg
    libwebp)
#    zlib"
#  if use system-ffmpeg; then
#    gn_system_libraries+=" ffmpeg"
#  fi

#more of those ^ system libs?: https://chromium.googlesource.com/chromium/src/+/lkgr/build/linux/unbundle/replace_gn_files.py

  if [ "${system_ffmpeg}" = "1" ]; then
    msg2only="${gn_system_libraries[@]}"
    msg2 "Using system libs: $msg2only"
    set -x
    build/linux/unbundle/replace_gn_files.py --system-libraries "${gn_system_libraries[@]}"
    set +x
    #these are invalid options now:
    #XXX: not anymore! because then I get this: "proprietary codecs and ffmpeg_branding set to Chromium are incompatible"
    #sed -re 's|^(ffmpeg_branding.*)|#\1|' -e 's|^(is_component_ffmpeg.*)|#\1|' -i "../args.gn"
  else
    msg2 "Using chromium's own ffmpeg"
    #these options are valid now (uncommenting them)
    sed -re 's|^#(ffmpeg_branding.*)|\1|' -e 's|^#(is_component_ffmpeg.*)|\1|' -i "../args.gn"
  fi


    cp -- "../args.gn" "${_reldir}"
##    "${srcdir}/pythonic"
      gn --root="${_srcfolder}" gen "${_reldir}"
      #args.gn generated from:
      gn args "${_reldir}" --list >/tmp/args_new.gn
      #and also without --list to edit it
#msg2 "ok wait"
#exit 1

  pwd
  echo "$PATH"
  export GYP_CHROMIUM_NO_ACTION=1
  #src: https://www.chromium.org/developers/gn-build-configuration
  msg2 "running: gclient runhooks (rerun ./1 if this is not executable: fetch_gclient_base/checkout_root/src/buildtools/linux64/gn ) (seems that depottools-git patch for stat isn't effective)" #fixed with patched depottools-git (note: rerun this lots if you get this skippable error: CommandException: Invalid command \"stat\")"
  #"${srcdir}/pythonic"
  gclient runhooks   #can't run this here because it runs gyp_chromium!

  if test ! -e "/usr/lib/libtinfo.so.5"; then
    msg2 "if you're getting something about libtinfo.so.5 missing in build() next, then you have to do this: cd /usr/lib && sudo ln -rs libtinfo.so libtinfo.so.5"
  fi
  #this is the error:
  #../../../home/z/build/1packages/chromium-dev-git/fetch_gclient_base/checkout_root/src/third_party/llvm-build/Release+Asserts/bin/clang++: error while loading shared libraries: libtinfo.so.5: cannot open shared object file: No such file or directory

}

build() {

  export PATH="${srcdir}/python-path:$PATH"
  msg2 "cleaning .d files from ${_reldir}"
  #because of errors like this:
  #ninja: error: gen/content/resources.d: depfile has multiple output paths
  cd "${_reldir}"
  #this won't work if there are no files:
#  find . -name '*.d' -type f -print0 | xargs -0 -- rm --one-file-system --verbose --
  find . -name '*.d' -type f -print0 -exec rm --one-file-system --verbose -- {} \;
  msg2 "continuing normally..."
  #cd "chromium-${pkgver}"
  cd "${_srcfolder}"
  echo "$CC"
  pwd
#  set
#  exit 2

  msg2 "Build the Launcher"
  make -C "${srcdir}/chromium-launcher-${_launcher_ver}" CHROMIUM_SUFFIX="" PREFIX=/usr ${_launcher_gtk}

#  cd "chromium-${pkgver}"

  # Set ccache environment
  if [ "${_use_ccache}" = "1" ]; then
    msg2 "Setup ccache"
    export CCACHE_CPP2=yes
    export CCACHE_SLOPPINESS=time_macros
  fi

  # Use system/bundled Clang? or GCC?
#  _bundled_clang_path="${srcdir}/chromium-${pkgver}/third_party/llvm-build/Release+Asserts/bin"

      msg2 "Setup for use system Clang"
      if [ "${_use_ccache}" = "0" ]; then
        export CC="clang -Qunused-arguments"
        export CXX="clang++ -Qunused-arguments"
      elif [ "${_use_ccache}" = "1" ]; then
        export CC="ccache clang -Qunused-arguments"
        export CXX="ccache clang++ -Qunused-arguments"
      fi
      export CXXFLAGS="${CXXFLAGS} -Wno-unknown-warning-option"

  # Changing bundle libraries to system ones
#  python2 build/linux/unbundle/replace_gyp_files.py ${_use_system[@]}

  # update libaddressinput strings
#  python2 third_party/libaddressinput/chromium/tools/update-strings.py

  #TODO: add to compilation: -fno-delete-null-pointer-checks
  #why? src: https://bugs.chromium.org/p/chromium/issues/detail?id=604165
  #SEGV_MAPERR
  #TODO: add this no-warning
  # -Wno-undefined-bool-conversion

  CFLAGS="${CFLAGS} -fno-delete-null-pointer-checks -Wno-undefined-bool-conversion"
  CXXFLAGS="${CXXFLAGS} -fno-delete-null-pointer-checks -Wno-undefined-bool-conversion" #ok this is useless then, since: export -n below(aka remove the export property from each NAME)
  # CFLAGS are passed through -Drelease_extra_cflags=
#  export -n CFLAGS CXXFLAGS
  #since it's GN not gyp, let's try export anyway:
  export CFLAGS CXXFLAGS

  msg2 "Starting building Chromium..."
  # Configure the builder
#  python2 build/gyp_chromium --depth=. -Drelease_extra_cflags="$CFLAGS" ${_flags[@]} ${_use_system[@]}


  msg2 "ninja-ing (if you get the following error, rerun ./1  this: /bin/sh: /home/z/build/1packages/chromium-dev-git/fetch_gclient_base/checkout_root/src/buildtools/linux64/gn: Permission denied"

  # Build all with ninja
  LC_ALL=C ninja -C "${_reldir}" -v chrome chrome_sandbox
  #LC_ALL=C ninja -C out/Release -v pdf chrome chrome_sandbox chromedriver widevinecdmadapter clearkeycdm

}

package() {
  # Install launcher
  msg2 "Install the Launcher"
  make -C "chromium-launcher-${_launcher_ver}" CHROMIUM_SUFFIX="" PREFIX=/usr DESTDIR="${pkgdir}" install-strip
#wtw  install -Dm644 "chromium-launcher-${_launcher_ver}/LICENSE" "${pkgdir}/usr/share/licenses/chromium/LICENSE.launcher"

  pushd "${_reldir}"
  #pushd "chromium-${pkgver}/out/Release" &> /dev/null

  # Install binaries
  install -Dm755 chrome "${pkgdir}/usr/lib/chromium/chromium"
  install -Dm644 chrome.1 "${pkgdir}/usr/share/man/man1/chromium.1"
  install -Dm4755 chrome_sandbox "${pkgdir}/usr/lib/chromium/chrome-sandbox"
#what is?  install -Dm755 chromedriver "${pkgdir}/usr/lib/chromium-dev/chromedriver"
#  ln -s /usr/lib/chromium-dev/chromedriver "${pkgdir}/usr/bin/chromedriver-dev"

   #ok this is useless, because needs LD_LIBRARY_PATH set! but it makes this .so when  is_component_ffmpeg = true #Default = false
   if test -e 'libffmpeg.so' ; then
     install -Dm755 libffmpeg.so "${pkgdir}/usr/lib/chromium/libffmpeg.so"
   fi

  # Install libs
#  for i in libwidevinecdmadapter libclearkeycdm; do
#    install -Dm755 "${i}.so" "${pkgdir}/usr/lib/chromium/${i}.so"
#  done
  install -Dm644 icudtl.dat "${pkgdir}/usr/lib/chromium/icudtl.dat" # https://crbug.com/584920 and https://crbug.com/592268
  install -Dm644 natives_blob.bin "${pkgdir}/usr/lib/chromium/natives_blob.bin"
  install -Dm644 snapshot_blob.bin "${pkgdir}/usr/lib/chromium/snapshot_blob.bin"
  #^ what is?

  # Install Resources
  for i in gen/content/content_resources keyboard_resources resources chrome_100_percent chrome_200_percent; do
    install -Dm644 "${i}.pak" "${pkgdir}/usr/lib/chromium/${i}.pak"
  done

  # Install locales
#don't have this:  find pseudo_locales -type f -name "*.pak" -exec install -Dm644 '{}' "${pkgdir}/usr/lib/chromium/{}" \;
  find locales -type f -name "*.pak" -exec install -Dm644 '{}' "${pkgdir}/usr/lib/chromium/{}" \;
  find resources -type f -name "*" -exec install -Dm644 '{}' "${pkgdir}/usr/lib/chromium/{}" \;
  (cd "${pkgdir}/usr/lib/chromium"; ln -s locales remote_locales)

  # Install icons
#  for _size in 16 22 24 32 48 128 256; do
#    case "${_size}" in
#      16|32) _branding="${srcdir}/chromium-${pkgver}/chrome/app/theme/default_100_percent/chromium" ;;
#      *) _branding="${srcdir}/chromium-${pkgver}/chrome/app/theme/chromium" ;;
#    esac
#    install -Dm644 "${_branding}/product_logo_${_size}.png" "${pkgdir}/usr/share/icons/hicolor/${_size}x${_size}/apps/chromium-dev.png"
#  done


  popd &> /dev/null

  # Install some external files
#  install -Dm644 "chromium-${pkgver}/chrome/installer/linux/common/desktop.template" "${pkgdir}/usr/share/applications/chromium-dev.desktop"
#  sed -e 's|@@MENUNAME@@|Chromium-dev|g' \
#      -e 's|@@USR_BIN_SYMLINK_NAME@@|chromium-dev|g' \
#      -e 's|@@PACKAGE@@|chromium-dev|g' \
#      -i "${pkgdir}/usr/share/applications/chromium-dev.desktop"
#  install -Dm644 chromium-dev.svg "${pkgdir}/usr/share/icons/hicolor/scalable/apps/chromium-dev.svg"
#  install -Dm644 "chromium-${pkgver}/LICENSE" "${pkgdir}/usr/share/licenses/chromium-dev/LICENSE"


  # Manually strip binaries so that 'nacl_irt_*.nexe' is left intact
  strip $STRIP_BINARIES "${pkgdir}/usr/lib/chromium/"{chromium,chrome-sandbox} #,chromedriver}
#  strip $STRIP_SHARED "${pkgdir}/usr/lib/chromium-dev/"lib{widevinecdmadapter,clearkeycdm}.so
}
